<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>随机生成小球</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

       
        #mycanvas{
            background-color: #000;
        }
</style>
    </style>
</head>

<body>
    <canvas id="mycanvas" width="600" height="600"></canvas>
    <script>
        // 1.获取元素
        let mycanvas = document.getElementById("mycanvas");
        let context = mycanvas.getContext("2d");
        // 2.管理小球
        let arr = [];
        // 2.1随机生成50个小球 rgba(255,255,255,.5)
        function getrandom(){
            //页面只能生成50个球
            if(arr.length>50){
                clearInterval(timer);
                return false;
            }
            let r = Math.floor(Math.random()*255);
            let g = Math.floor(Math.random()*255);
            let b = Math.floor(Math.random()*255);
            let bg = `rgba(255,255,255,${Math.random()})`;
 
            //小球的半径
            let xr = Math.floor(Math.random()*20);
            //小球的圆心坐标
            let cx = Math.floor(Math.random()*200) + 200;
            let cy = Math.floor(Math.random()*200) + 200;
            //小坐标的移动距离(正反方向都可移动，数值可为正数和负数，数值不能过大，否则小球移动距离会大，动画效果不连贯)
            // Math.floor(Math.random()*4); 0,1,2,3;向下取整
            let sx = -2 + Math.floor(Math.random()*4);
            let sy = -2 + Math.floor(Math.random()*4);
            let obj = {
                bg: bg,
                xr: xr,
                cx: cx,
                cy: cy,
                sx: sx,
                sy: sy
            }
            //小球坐标移动距离为0的时候，不把小球放进去，否则小球不会动
            if(sx === 0 || sy === 0){
                arr.push(obj);
            }
            console.log("arr",arr);
        }
        let timer = setInterval(getrandom,30);
 
        // 2.2 将生成的50个小球画到画布上
        function drawBall(){
            context.clearRect(0,0,600,600);
            for(let i = 0;i<arr.length;i++){
                //小球碰撞到边框改变方向(改变方向：让移动的距离取反)
                if(arr[i].cx + arr[i].xr > 600 || arr[i].cx - arr[i].xr <= 0){
                    arr[i].sx = arr[i].sx*-1;
                }
                if(arr[i].cy + arr[i].xr >600 || arr[i].cy - arr[i].xr <= 0){
                    arr[i].sy = arr[i].sy*-1;
                }
                //改变小球的圆心坐标
                arr[i].cx = arr[i].cx + arr[i].sx;
                arr[i].cy = arr[i].cy + arr[i].sy;
                //画球
                context.beginPath();
                context.arc(arr[i].cx,arr[i].cy,arr[i].xr,0,Math.PI*2,false);
                context.fillStyle = arr[i].bg;
                context.fill();
                context.closePath();
            }
        }
        //间隔30秒去画小球，因为小球的位置不一样，就产生了动画的效果
        setInterval(drawBall,30);
    </script>
</body>

</html>